<script setup>
import {Message} from '@arco-design/web-vue'
import {computed, ref} from 'vue'
import {route} from "ziggy-js";

const props = defineProps({
    // 文件大小限制（MB）
    maxSize: {
        type: Number,
        default: 5
    },
})

const modelValue = defineModel('modelValue', { type: String, default: '' })

const action = route('admin.upload.image')
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
const headers = {
    'X-CSRF-TOKEN': csrfToken,
}

// 响应式状态
const isUploading = ref(false)
const errorMessage = ref('')

// 计算属性
const hasImage = computed(() => !!modelValue.value)

// 事件处理
const handleSuccess = (currentFile) => {
    if (currentFile.response.code === 200) {
        modelValue.value = currentFile.response.data.url
        Message.success('图片上传成功')
        errorMessage.value = ''
    } else {
        Message.error('图片上传失败')
        errorMessage.value = '上传失败，请重试'
    }
    isUploading.value = false
}

const handleError = () => {
    Message.error('图片上传失败')
    errorMessage.value = '上传失败，请重试'
    isUploading.value = false
}

const handleBeforeUpload = (file) => {
    // 重置状态
    errorMessage.value = ''
    isUploading.value = true

    // 文件大小验证
    const maxSizeInBytes = props.maxSize * 1024 * 1024
    if (file.size > maxSizeInBytes) {
        Message.error(`文件大小不能超过 ${props.maxSize}MB`)
        isUploading.value = false
        return false
    }

    return true
}

const handleRemove = (e) => {
    e.stopPropagation()
    modelValue.value = ''
    Message.info('已移除图片')
}
</script>

<template>
    <div class="simple-image-upload">
        <a-upload
            :action="action"
            :before-upload="handleBeforeUpload"
            :disabled="isUploading"
            :headers="headers"
            :show-file-list="false"
            :with-credentials="true"
            accept="image/*"
            name="file"
            @error="handleError"
            @success="handleSuccess"
        >
            <template #upload-button>
                <div class="upload-box">
                    <!-- 上传中状态 -->
                    <div v-if="isUploading" class="uploading-state">
                        <a-spin size="large" />
                        <div class="upload-text">上传中...</div>
                    </div>

                    <!-- 已上传图片状态 -->
                    <div v-else-if="hasImage" class="image-state">
                        <img :src="modelValue" alt="预览图片" class="preview-image" />
                        <div class="image-actions size-full flex justify-center items-center gap-2">
                            <a-button
                                class="remove-btn"
                                size="mini"
                                type="outline"
                                @click="handleRemove"
                            >
                                <icon-eye />
                            </a-button>
                            <a-button
                                class="remove-btn"
                                size="mini"
                                status="danger"
                                type="outline"
                                @click="handleRemove"
                            >
                                <icon-delete />
                            </a-button>
                        </div>
                    </div>

                    <!-- 默认上传状态 -->
                    <div v-else class="default-state">
                        <div class="upload-icon">
                            <icon-plus />
                        </div>
                        <div class="upload-text">上传图片</div>
                    </div>
                </div>
            </template>
        </a-upload>

        <!-- 错误提示 -->
        <div v-if="errorMessage" class="error-tip">
            <icon-exclamation-circle-fill />
            <span>{{ errorMessage }}</span>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.simple-image-upload {
    display: inline-flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
}

.upload-box {
    position: relative;
    width: 120px;
    height: 120px;
    border: 2px dashed var(--color-border-3);
    border-radius: 8px;
    background: var(--color-fill-2);
    transition: all 0.3s ease;
    cursor: pointer;
    overflow: hidden;

    &:hover {
        border-color: var(--color-primary-light-3);
        background: var(--color-fill-1);
    }
}

.uploading-state,
.default-state,
.image-state {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.upload-text {
    font-size: 12px;
    color: var(--color-text-3);
}

.upload-icon {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: var(--color-primary-light-5);
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--color-primary);
    font-size: 16px;
}

.preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.image-state {
    position: relative;
    &:hover .image-actions {
        opacity: 1;
        background: rgba(0, 0, 0, .5);
    }
}

.image-actions {
    position: absolute;
    opacity: 0;
    transition: opacity 0.3s ease;
}

.remove-btn {
    border: none;
    background: unset;
    color: #fff;
    font-size: 18px;
}

.error-tip {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 12px;
    color: var(--color-danger);

    .arco-icon {
        font-size: 12px;
    }
}

.custom-tip {
    font-size: 12px;
    color: var(--color-text-3);
    line-height: 1.4;
}
</style>
